// import fs from "fs"
import { swaggerConfig } from '../../swaggerConfig'
import utilTool from '../../util/tool'
import { SwResult } from "../../store/swResult"
import { IJson, IEnumObj } from "../../interface/type"
import { enumTemp } from "../template/enumTemp"

function getEnumJson(sw: SwResult): IJson {
  const json: IJson = {}
  const definitions: IJson = sw.getDefinitions()
  console.log('枚举JSON:', definitions)
  for (const key of Object.keys(definitions)) {
    const item = definitions[key]
    if (!item?.properties) continue
    for (const prokey of Object.keys(item?.properties)) {
      const it = item?.properties[prokey]
      if (it?.enum?.length > 0 && it?.description) {
        // 如果是枚举
        const description = utilTool.trimStr(it?.description)
        let enumOjb: IEnumObj
        if (description.indexOf('：') > -1) {
          enumOjb = utilTool.handleOldRuleEnum(description, it.enum)
        } else {
          enumOjb = utilTool.handleEnum(description, it.enum)
        }
        json[utilTool.firstUp(prokey) + 'Enum'] = enumOjb
      }
    }
  }
  return json
}

export async function createEnumJosnFile(sw: SwResult) {
  // 格式化json
  // const josnText = 'export default ' + getEnumJson(sw)
  // 指定要创建的目录和文件名称 __dirname为执行当前js文件的目录
  const filePath = await utilTool.checkAndCreatePath('/src/assets/js/enum')
  const fileName = utilTool.upToLine(`co-${swaggerConfig.serverName}Enum.js`)
  utilTool.generateFile(filePath + `/${fileName}`, enumTemp(getEnumJson(sw)))

  // const file = utilTool.resolvePath(filePath, fileName)
  // 写入文件
  // fs.writeFile(file, josnText,  (err) => {
  //   if (err) {
  //     console.log(err);
  //   } else {
  //     console.log('文件创建成功~' + file);
  //   }
  // })
}
